package com.zgx.plus.common.utils;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zgx.plus.common.response.page.PageDomain;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class ServletUtils {

    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String IS_ASC = "isAsc";


    public static PageDomain buildPageHelperRequest() {
        PageDomain pageDomain = new PageDomain();
        pageDomain.setPageNum(Convert.toInt(getRequest().getParameter(PAGE_NUM), 1));
        pageDomain.setPageSize(Convert.toInt(getRequest().getParameter(PAGE_SIZE), 10));
        pageDomain.setOrderByColumn(getRequest().getParameter(ORDER_BY_COLUMN));
        pageDomain.setIsAsc(getRequest().getParameter(IS_ASC));
        pageDomain.setReasonable(true);// 对于不合理的分页参数自动处理，比如传递pageNum是小于0，会默认设置为1.
        return pageDomain;
    }

    /**
     * 获取request
     */
    public static Page<?> buildPageRequest() {
        return Page.of(Convert.toLong(getRequest().getParameter(PAGE_NUM), 1L),
                Convert.toLong(getRequest().getParameter(PAGE_NUM), 10L));
    }

    /**
     * 服务地址: 获取完整的请求路径，包括：域名，端口，上下文访问路径
     */
    public String getUrl() {
        HttpServletRequest request = getRequest();
        StringBuffer webURL = request.getRequestURL();//web可访问的路径
        String requestURI = request.getRequestURI();//requestMapping映射的的路径
        return webURL.delete(webURL.length() - requestURI.length(), webURL.length()).append(request.getServletContext().getContextPath()).toString();
    }

    /**
     * 获得所有请求参数
     *
     * @param request 请求对象{@link ServletRequest}
     * @return Map
     */
    public static Map<String, String> getParamMap(ServletRequest request) {
        Map<String, String> params = new HashMap<>();
        for (Map.Entry<String, String[]> entry : Collections.unmodifiableMap(request.getParameterMap()).entrySet()) {
            params.put(entry.getKey(), String.join(",", entry.getValue()));
        }
        return params;
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取session
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 将字符串渲染到客户端
     *
     * @param response 渲染对象
     * @param string   待渲染的字符串
     */
    public static void renderString(HttpServletResponse response, String string) {
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
